package middleware

import (
	"aiRole/internal/dao/model"
	result "aiRole/internal/dto/reslult"
	initSystem "aiRole/pkg/init"
	"aiRole/pkg/util"
	"context"
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"net/http"
	"time"
)

func TokenAuthMiddleware(c *gin.Context) {
	authHeader := c.GetHeader("Authorization")
	if c.Request.URL.Path == "/ai/v2/chat" {
		c.Next()
		return
	}
	if authHeader == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
		c.Abort()
		return
	}
	jwtInfo, err := util.ParseJWT(authHeader)
	if err != nil {
		result.Error(c, 401, "token无效")
		return
	}
	uid := jwtInfo.UserId

	rst, err := initSystem.RDB.Get(context.TODO(), "user:"+uid).Result()
	if errors.Is(err, redis.Nil) {
		result.Error(c, 401, "登录超时")
		c.Abort()
		return
	} else if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "服务器异常")
		return
	} else {
		var data model.User
		err := json.Unmarshal([]byte(rst), &data)
		if err != nil {
			initSystem.Logger.Error(err.Error())
			result.Error(c, 500, "服务器异常")
		}
		c.Set("userinfo", data)
		//token续期
		_, err = initSystem.RDB.Expire(context.TODO(), "user:"+uid, time.Hour*24*3).Result()
		if err != nil {
			initSystem.Logger.Error(err.Error())
			result.Error(c, 500, "服务器异常")
		}
		c.Next()
	}
}
